package com.ruitu.mall_98_seller.support.rong;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.R;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.RichContentMessage;

public class ConversationActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tv_title;

    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        toolbar = findViewById(R.id.toolbar);
        tv_title = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.arad_ic_back_normal);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        toolbar.setTitle("");

        String titile = "客服";
        String mtargetId = "";
        try {
            titile = getIntent().getData().getQueryParameter("title");
            mtargetId = getIntent().getData().getQueryParameter("targetId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_title.setText(titile);

        FragmentManager fragmentManage = getSupportFragmentManager();
        ConversationFragment fragement = (ConversationFragment) fragmentManage.findFragmentById(R.id.conversation);
        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(Conversation.ConversationType.PRIVATE.getName().toLowerCase())
                .appendQueryParameter("targetId", mtargetId).build();

        fragement.setUri(uri);

        RongIM.getInstance().setSendMessageListener(new RongIM.OnSendMessageListener() {
            @Override
            public Message onSend(Message msg) {
                return msg;
            }

            @Override
            public boolean onSent(Message msg, RongIM.SentMessageErrorCode sentMessageErrorCode) {
                byte[] msgByte = msg.getContent().encode();
                String msgContent = new String(msgByte);
//                RongMsgContent realContent = gson.fromJson(msgContent, RongMsgContent.class);
//                Logg.i("msgContent = " + msgContent);
//                Logg.i("onSent执行了....." + "发送人:" + msg.getSenderUserId() + ",接收者:" + msg.getTargetId() + ",内容:" + realContent.getContent());

                if (null == sentMessageErrorCode) {
                    return true;
                }
                return false;
            }
        });

//        final Product p = P_Global.P;
//        final String targetId = P_Global.T_ID;
//        if (null != p && !TextUtils.isEmpty(targetId)) {
//            sendWelcomeMsg(targetId);//请求欢迎消息
//            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "是否发送当前商品信息给商家？", "发送",
//                    "取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            sendPicTxtMsg(p, targetId);
//                        }
//                    }, null);
//        }

        setListeners();//设置会话界面监听
    }

    private void setListeners() {
        RongIM.getInstance().setConversationClickListener(new RongIM.ConversationClickListener() {
            @Override//点击用户头像
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override//长按用户头像
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override//点击消息
            public boolean onMessageClick(Context context, View view, Message message) {
                MessageContent msgContent = message.getContent();
                if (msgContent instanceof RichContentMessage) {
                    //点击的是图文消息,此项目可以认为是发送的商品
                    String extra = ((RichContentMessage) msgContent).getExtra();
                    if (TextUtils.isEmpty(extra)) {
                        ToastUtils.showShortSafe("商品信息有误!");
                    } else {
                        // 卖家端暂时没有商品和详情页面,暂时无法进行跳转
//                        Product product = new Product();
//                        product.setGoodId(extra);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("product", product);
//                        Intent intent = new Intent(ConversationActivity.this, ProductDetailActivity.class);
//                        intent.putExtras(bundle);
//                        startActivity(intent);
                    }
                    return true;
                }
                return false;
            }

            @Override//点击链接消息
            public boolean onMessageLinkClick(Context context, String s, Message message) {
                return false;
            }

            @Override//长按消息
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });
    }

    // 发送图文信息,即商品信息
//    private void sendPicTxtMsg(Product p, String targetId) {
//        RichContentMessage richMsg = RichContentMessage.obtain(p.getGoodName()
//                , "价格￥" + p.getGoodMarket(), Config.BASE_URL + p.getImageUrl());
//        richMsg.setExtra(p.getGoodId());//设置消息存储的信息,这里存商品id
//        Message myMsg = Message.obtain(targetId, Conversation.ConversationType.PRIVATE, richMsg);
//        RongIM.getInstance().sendMessage(myMsg, null, null, new IRongCallback.ISendMessageCallback() {
//            @Override
//            public void onAttached(Message message) {
//                //消息本地数据库存储成功的回调
//            }
//
//            @Override
//            public void onSuccess(Message message) {
////                ToastUtils.showShort("消息发送成功" + ((RichContentMessage) message.getContent()).getTitle());
//
//            }
//
//            @Override
//            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
////                ToastUtils.showShort("消息发送失败");
//            }
//        });
//    }

    private void sendWelcomeMsg(String targetId) {//提醒卖家发送欢迎消息
//        if (P_Global.LAST_TIME > 0 && null != P_Global.T_ID_OLD) {
//            if (TextUtils.equals(P_Global.T_ID_OLD, targetId) && System.currentTimeMillis() - P_Global.LAST_TIME < 60000) {
//                //同一件商品,一分钟以内咨询多次
//                return;
//            }
//        } else {
//            P_Global.LAST_TIME = System.currentTimeMillis();
//            P_Global.T_ID_OLD = targetId;
//        }

//        APIRetrofit.getDefault().reqMsgWelcome(targetId, AppHolder.instance().getUser().getAccountId())
//                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new SubscriberImpl<BaseResult>() {
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onNext(BaseResult baseResult) {
//                        Logg.i(baseResult.getMsg());
//                        if (baseResult.isSuccess()) {
//
//                        } else {
//
//                        }
//                    }
//                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        P_Global.P = null;
    }
}
